package com.dq.ad;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.mbms.DownloadStatusListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdInteractionListener;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.dq.ad.bean.RewardBundleModel;
import com.dq.ad.dialog.BaseAdDialogLoading;
import com.dq.ad.utils.TTAdManagerHolder;
import com.dq.ad.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class AdManager {

    private static final String TAG = "AdManager";
    public static volatile String channel;

    private OnFullscreenVideoADListener fvAdListener;
    private OnRewardVideoADListener rvAdListener;

    private boolean isRewardClosed = false;//激励视频是否点了关闭
    private boolean isRewardSendSus = false;//激励视频是否上报成功
    private boolean isRewardCallBacked = false;//激励视频是否已经回调onClose()


    private  OnRewardVideoADListener listener;

    public static int NATIVE_AD_TYPE_UP_IMAGE = 0;

//    public float getScreenWidthDp(Context context) {
////        return DisplayUtil.getScreenWidthDp(context);
//    }

    private static final class AdManagerHolder {
        static final AdManager INSTANCE = new AdManager();
    }

    public static AdManager getInstance() {
        return AdManagerHolder.INSTANCE;
    }

    public void useTextureView(boolean use) {
//        HXADConfig.useTextureView(use);
    }

    public void supportMultiProcess(boolean support) {
//        HXADConfig.supportMultiProcess(support);
    }

    public void initSDK(Context context, String appId, String chId, String cpId, boolean isDebug, boolean isLog) {
        initSDK(context, appId, chId, cpId, isDebug, isLog, true);
    }

    /**
     * 初始化广告SDK
     *
     * @param context context
     * @param appId   hxAppId
     * @param chId    渠道号
     * @param cpId    CP号
     * @param isDebug 是否测试服广告 默认值false
     * @param isLog   是否打印log 建议BuildConfig.DEBUG
     * @param isCrash 是否拦截崩溃异常 默认值true
     */
    public void initSDK(final Context context, final String appId, final String chId, final String cpId, final boolean isDebug, final boolean isLog, final boolean isCrash) {
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
//        TTAdSdk.init(context,
//                new TTAdConfig.Builder()
//                        .appId(appId)//xxxxxxx为穿山甲媒体平台注册的应用ID
//                        .useTextureView(true) //默认使用SurfaceView播放视频广告,当有SurfaceView冲突的场景，可以使用TextureView
//                        .appName("悟空來了")
//                        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)//落地页主题
//                        .allowShowNotify(true) //是否允许sdk展示通知栏提示,若设置为false则会导致通知栏不显示下载进度，存在违规风险，请勿随意更改
//                        .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
//                        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合,没有设置的网络下点击下载apk会有二次确认弹窗，弹窗中会披露应用信息
//                        .supportMultiProcess(false)//是否支持多进程，true支持
//                        .build());
//        TTAdSdk.start(new TTAdSdk.Callback() {
//            @Override
//            public void success() {
//                Log.e("adNativeLoader","成功");
//            }
//
//            @Override
//            public void fail(int i, String s) {
//
//            }
//        });


        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限
        TTAdManagerHolder.get().requestPermissionIfNecessary(context);
        //step3:创建TTAdNative对象,用于调用广告请求接口

        mTTAdNative = ttAdManager.createAdNative(context);
    }

    /**
     * 显示原生广告
     */
    public void showNativeAD(Activity activity, ViewGroup viewGroup) {
//        if (nad.isPreloaded())
//            nad.showAD(activity, viewGroup);
//        else
//            nad.loadAD();
    }

    public void showFullscreenVideoAD(Activity activity) {
        showFullscreenVideoAD(activity, null);
    }

    /**
     * 显示全屏视频广告
     */
    public void showFullscreenVideoAD(Activity activity, OnFullscreenVideoADListener listener) {
//        if (fvAd.isPreloaded()) {
//            if (listener != null) {
//                fvAdListener = listener;
//            }
//            fvAd.showAD(activity);
//        } else {
//            loadFullscreenVideoAD(activity, false, listener);
//        }
    }

    public void showRewardVideoAD(String rewardName, Activity activity) {
        rvAdListener = null;
        showRewardVideoAD(rewardName, "-1", activity, null);
    }

    private String getUserData(){
        JSONArray jsonArray = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("name", "auth_reward_gold");
            object.put("value", "3000");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        jsonArray.put(object);

        return jsonArray.toString();
    }

    public void showRewardVideoAD(String rewardName, Activity activity, OnRewardVideoADListener listener) {
//        showRewardVideoAD(rewardName, "-1", activity, listener);
        loadAd(rewardName,activity);
        mAdLoadListener.setListener(listener);

    }
    private TTAdNative mTTAdNative;
    private AdLoadListener mAdLoadListener;

    private void loadAd(final String codeId,Activity  activity) {
        //step5:创建广告请求参数AdSlot

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId) // 广告代码位Id
                .setAdLoadType(TTAdLoadType.LOAD) // 本次广告用途：TTAdLoadType.LOAD实时；TTAdLoadType.PRELOAD预请求
                .setUserData(getUserData())
                .setRewardName("金币")
                .build();
        //step6:注册广告加载生命周期监听，请求广告

           mAdLoadListener = new AdLoadListener(activity);

        mTTAdNative.loadRewardVideoAd(adSlot, mAdLoadListener);
    }


    private static class AdLoadListener implements TTAdNative.RewardVideoAdListener {

        private final Activity mActivity;
        private  OnRewardVideoADListener mListener;

        private TTRewardVideoAd mAd;

        private TTAdInteractionListener mInteractionListener =  new TTAdInteractionListener() {
            @Override
            public void onAdEvent(int code, Map map) {

                if (code == TTAdConstant.AD_EVENT_AUTH_DOUYIN && map != null) {
                    // 抖音授权成功状态回调, 媒体可以通过map获取抖音openuid用以判断是否下发奖励
                    String uid = (String) map.get("open_uid");
                    Log.i(TAG, "授权成功 --> uid：" + uid);
                }
            }
        };
        public AdLoadListener(Activity activity) {
            mActivity = activity;
        }

        public void setListener( OnRewardVideoADListener listener) {
            mListener = listener;
        }

        /**
         * 广告加载过程中出错
         */
        @Override
        public void onError(int code, String message) {
            Log.e(TAG, "Callback --> onError: " + code + ", " + message);
            mListener.onFailed(code,code);
        }

        /**
         * 广告基础信息加载完成，此方法是回调后是广告可调用展示的最早时机
         *
         * @param ad 广告对象 在一次广告生命周期中onRewardVideoAdLoad与onRewardVideoCached回调中的ad是同一个对象
         */
        @Override

        public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
            Log.e(TAG, "Callback --> onRewardVideoAdLoad");

//            ToastUtil.showShortToast(mActivity, "rewardVideoAd loaded 广告类型：" + getAdType(ad.getRewardVideoAdType()));
            handleAd(ad,mListener);
        }

        @Override

        public void onRewardVideoCached() {
            // 已废弃 请使用 onRewardVideoCached(TTRewardVideoAd ad) 方法
        }

        /**
         * 广告基础信息与素材缓存完成，此时调用广告展示流畅，是展示广告的最理想时机
         *
         * @param ad 广告对象 在一次广告生命周期中onRewardVideoAdLoad与onRewardVideoCached回调中的ad是同一个对象
         */
        @Override

        public void onRewardVideoCached(TTRewardVideoAd ad) {
            Log.e(TAG, "Callback --> onRewardVideoCached");

//            ToastUtil.showShortToast(mActivity, "rewardVideoAd cached 广告类型：" + getAdType(ad.getRewardVideoAdType()));
            handleAd(ad,mListener);
        }

        /**
         * 处理广告对象
         */

        public void handleAd(TTRewardVideoAd ad, OnRewardVideoADListener mListener) {
            if (mAd != null) {
                return;
            }
            mAd = ad;
            //【必须】广告展示时的生命周期监听

            mAd.setRewardAdInteractionListener(new AdLifeListener(mActivity,mListener));

            //【可选】再看一个展示时的生命状态监听

            PlayAgainAdLifeListener playAgainAdLifeListener = new PlayAgainAdLifeListener(mActivity);
            mAd.setRewardPlayAgainInteractionListener(playAgainAdLifeListener);
            //【可选】再看一个入口与奖励显示控制器

            PlayAgainController playAgainController = new PlayAgainController();
            playAgainController.setPlayAgainAdLifeListener(playAgainAdLifeListener);
            mAd.setRewardPlayAgainController(playAgainController);
            //【可选】监听下载状态
            mAd.setDownloadListener(new AdManager.DownloadStatusListener());

            /**
             * 注册广告事件监听， 目前只有授权事件定义，后续会扩展
             */
            mAd.setAdInteractionListener(mInteractionListener);
            showAd();
        }

        /**
         * 触发展示广告
         */
        public void showAd() {
            if (mAd == null) {
                ToastUtil.showShortToast(mActivity, "当前广告未加载好，请先点击加载广告");
                return;
            }

            mAd.showRewardVideoAd(mActivity);
            // 广告使用后应废弃
            mAd = null;
        }
    }

    /**
     * 【可选】下载状态监听器
     */
    private static class DownloadStatusListener implements TTAppDownloadListener {

        @Override
        public void onIdle() {
        }

        @Override
        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
            Log.d("DML", "onDownloadActive==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
        }

        @Override
        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
            Log.d("DML", "onDownloadPaused===totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
        }

        @Override
        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
            Log.d("DML", "onDownloadFailed==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
        }

        @Override
        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
            Log.d("DML", "onDownloadFinished==totalBytes=" + totalBytes + ",fileName=" + fileName + ",appName=" + appName);
        }

        @Override
        public void onInstalled(String fileName, String appName) {
            Log.d("DML", "onInstalled==" + ",fileName=" + fileName + ",appName=" + appName);
        }
    }
    /**
     * 【必须】广告生命状态监听器
     */

    private static class AdLifeListener implements TTRewardVideoAd.RewardAdInteractionListener {

        private final WeakReference<Context> mContextRef;
        private WeakReference<OnRewardVideoADListener>  mListener;

        public AdLifeListener(Context context,OnRewardVideoADListener mListener) {
            mContextRef = new WeakReference<>(context);
            this.mListener=new WeakReference<>(mListener);
        }

        @Override

        public void onAdShow() {
            // 广告展示
            Log.d(TAG, "Callback --> rewardVideoAd show");
//            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd show");
        }

        @Override

        public void onAdVideoBarClick() {
            // 广告中产生了点击行为
            Log.d(TAG, "Callback --> rewardVideoAd bar click");
            mListener.get().onClosed("200");
            ToastUtil.showShortToast(mContextRef.get(), "红包奖励");
        }

        @Override

        public void onAdClose() {
            // 广告整体关闭
            Log.d(TAG, "Callback --> rewardVideoAd close");
            mListener.get().onFailed(404,404);
//            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd close");
        }

        //视频播放完成回调
        @Override
        public void onVideoComplete() {
            // 广告素材播放完成，例如视频未跳过，完整的播放了
            mListener.get().onReward();
            mListener.get().onClosed("200");
            Log.d(TAG, "Callback --> rewardVideoAd complete");
//            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd complete");
        }

        @Override
        public void onVideoError() {
            // 广告素材展示时出错
            Log.e(TAG, "Callback --> rewardVideoAd error");
            mListener.get().onFailed(404,404);
//            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd error");
        }

        @Override

        public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
            // 已废弃 请使用 onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo)
        }

        @Override

        public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
            // 用户的观看行为满足了奖励条件
            RewardBundleModel rewardBundleModel = new RewardBundleModel(extraInfo);
            Log.e(TAG, "Callback --> rewardVideoAd has onRewardArrived " +
                    "\n奖励是否有效：" + isRewardValid +
                    "\n奖励类型：" + rewardType +
                    "\n奖励名称：" + rewardBundleModel.getRewardName() +
                    "\n奖励数量：" + rewardBundleModel.getRewardAmount() +
                    "\n建议奖励百分比：" + rewardBundleModel.getRewardPropose());
            ToastUtil.showShortToast(mContextRef.get(), "ad onRewardArrived valid:" + isRewardValid +
                    " type:" + rewardType + " errorCode:" + rewardBundleModel.getServerErrorCode());
            if (!isRewardValid) {
                Log.d(TAG, "发送奖励失败 code：" + rewardBundleModel.getServerErrorCode() +
                        "\n msg：" + rewardBundleModel.getServerErrorMsg());
                return;
            }


            if (rewardType == TTRewardVideoAd.REWARD_TYPE_DEFAULT) {
                Log.d(TAG, "普通奖励发放，name:" + rewardBundleModel.getRewardName() +
                        "\namount:" + rewardBundleModel.getRewardAmount());
            }
        }

        @Override
        public void onSkippedVideo() {
            // 用户在观看素材时点击了跳过
            Log.e(TAG, "Callback --> rewardVideoAd has onSkippedVideo");
            mListener.get().onFailed(404,404);
            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd has onSkippedVideo");
        }
    }

    /**
     * 【可选】再看广告生命状态监听器
     */

    private static class PlayAgainAdLifeListener implements TTRewardVideoAd.RewardAdInteractionListener {

        private final WeakReference<Context> mContextRef;
        private int mNowPlayAgainCount = 0;
        private int mNextPlayAgainCount = 1;

        public PlayAgainAdLifeListener(Context context) {
            mContextRef = new WeakReference<>(context);
        }

        @Override

        public void onAdShow() {
            mNowPlayAgainCount = mNextPlayAgainCount;
            Log.d(TAG, "Callback --> 第 " + mNowPlayAgainCount + " 次再看 rewardPlayAgain show");
            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd show");
        }

        @Override

        public void onAdVideoBarClick() {
            Log.d(TAG, "Callback --> 第 " + mNowPlayAgainCount + " 次再看 rewardPlayAgain bar click");
            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd bar click");
        }

        @Override

        public void onAdClose() {
            // 再看广告不会调到这个回调
        }

        //视频播放完成回调
        @Override
        public void onVideoComplete() {
            Log.d(TAG, "Callback --> 第 " + mNowPlayAgainCount + " 次再看 rewardPlayAgain complete");
            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd complete");
        }

        @Override
        public void onVideoError() {
            Log.e(TAG, "Callback --> 第 " + mNowPlayAgainCount + " 次再看 rewardPlayAgain error");
            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd error");
        }

        @Override

        public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
            // 已废弃 请使用 onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) 方法
        }

        @Override
        public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
            RewardBundleModel rewardBundleModel = new RewardBundleModel(extraInfo);
            Log.e(TAG, "Callback --> 第 " + mNowPlayAgainCount + " 次再看 rewardPlayAgain has onRewardArrived " +
                    "\n奖励是否有效：" + isRewardValid +
                    "\n奖励类型：" + rewardType +
                    "\n奖励名称：" + rewardBundleModel.getRewardName() +
                    "\n奖励数量：" + rewardBundleModel.getRewardAmount() +
                    "\n建议奖励百分比：" + rewardBundleModel.getRewardPropose());
            ToastUtil.showShortToast(mContextRef.get(), "ad again" + mNowPlayAgainCount + " onRewardArrived valid:" + isRewardValid +
                    " type:" + rewardType + " errorCode:" + rewardBundleModel.getServerErrorCode());

            if (rewardType == TTRewardVideoAd.REWARD_TYPE_DEFAULT) {
                Log.d(TAG, "再看一个普通奖励发放，name:" + rewardBundleModel.getRewardName() +
                        "\namount:" + rewardBundleModel.getRewardAmount());
            }
        }

        @Override
        public void onSkippedVideo() {
            Log.e(TAG, "Callback --> 第 " + mNowPlayAgainCount + " 次再看 rewardPlayAgain has onSkippedVideo");
            ToastUtil.showShortToast(mContextRef.get(), "rewardVideoAd has onSkippedVideo");
        }

        public void setNextPlayAgainCount(int nextPlayAgainCount) {
            mNextPlayAgainCount = nextPlayAgainCount;
        }
    }

    /**
     * 【可选】再看广告入口控制器
     */

    private static class PlayAgainController implements TTRewardVideoAd.RewardAdPlayAgainController {

        private PlayAgainAdLifeListener mPlayAgainAdLifeListener;

        public void setPlayAgainAdLifeListener(PlayAgainAdLifeListener playAgainAdLifeListener) {
            mPlayAgainAdLifeListener = playAgainAdLifeListener;
        }

        @Override
        public void getPlayAgainCondition(int nextPlayAgainCount, Callback callback) {
            Bundle bundle = new Bundle();
            bundle.putBoolean(KEY_PLAY_AGAIN_ALLOW, true);
            bundle.putString(KEY_PLAY_AGAIN_REWARD_NAME, "金币");
            bundle.putString(KEY_PLAY_AGAIN_REWARD_AMOUNT, nextPlayAgainCount + "");
            if (mPlayAgainAdLifeListener != null) {
                mPlayAgainAdLifeListener.setNextPlayAgainCount(nextPlayAgainCount);
            }
            callback.onConditionReturn(bundle);
        }
    }


/*****************************/

    /**
     * 显示激励视频广告
     */
    public void showRewardVideoAD(String rewardName, String rewardAmount, Activity activity, OnRewardVideoADListener listener) {
        Log.i(TAG, "showRewardVideoAD");
        isRewardClosed = false;
        isRewardCallBacked = false;
        isRewardSendSus = false;
        rvAdListener = null;

        Map<String, String> map = new HashMap<>();
//        map.put("user_id", HXCurrencySDK.getInstance().getUserId());
        map.put("reward_name", rewardName);
        map.put("reward_amount", rewardAmount);
        map.put("reward_extra", "1");  //1:广告校验，0：广告不校验
//        getRvAd().setRewardParams(rewardAmount.equals("-1") ? null : map);

        showLoading(activity);
//        if (rvAd != null && rvAd.isPreloaded()) {
//            if (listener != null) {
//                rvAdListener = listener;
//            }
//            Log.e(TAG, "预加载成功，直接显示激励视频");
//            closeLoading("", activity);
//            rvAd.showAD(activity);
//        } else {
//            Log.e(TAG, "预加载失败，直接加载激励视频");
//            loadRewardVideoAD(activity, false, listener);
//        }
    }

    private BaseAdDialogLoading dialogLoading;
    private Handler handler;

    private void showLoading(final Activity activity) {
        Log.e(TAG, "广告正在加载，展示广告Loading");

        if (activity.isFinishing()) {
            return;
        }

        if (dialogLoading == null) {
            dialogLoading = new BaseAdDialogLoading(activity);
        }

        dialogLoading.show();

        if (handler == null) {
            handler = new Handler();
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "超时关闭Loading");
//                if (rvAd != null) {
//                    rvAd.destroy();
//                    rvAd = null;
//                }
//                if (rvAdListener != null) {
//                    rvAdListener = null;
//                }
                closeLoading("加载广告超时", activity);
            }
        }, 8000);
    }

    private void closeLoading(String value, Activity activity) {
        if (!TextUtils.isEmpty(value)) {
//            ToastUtil.showShort(activity, value);
        }

        if (dialogLoading != null && !activity.isFinishing()) {
            dialogLoading.dismiss();
            dialogLoading = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    /**
     * 预加载视频广告
     *
     * @param activity a
     */
    public void preloadVideoAd(final Activity activity) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
//                loadFullscreenVideoAD(activity, true);
                loadRewardVideoAD(activity, true);
            }
        });
    }

//    public boolean getHxAdOpen() {
////        return HXADConfig.isAdOpen();
//    }

    /**
     * 加载开屏广告
     *
     * @param activity    activity
     * @param adContainer 容器
     * @param adListener  监听回调
     */
//    public void showSplashAD(Activity activity, ViewGroup adContainer, final SplashADListener adListener) {
////        new SplashAD(activity, HXADConfig.getAicsKey(activity, HXADConfig.AD_TYPE.SPLASH), adContainer, new SplashADListener() {
////            @Override
////            public void onNoAD(AdError adError) {
////                Log.e(TAG, "onNoAD:");
////                if (adListener != null) {
////                    adListener.onNoAD(adError);
////                }
////            }
////
////            @Override
////            public void onADPresent(AdLogInfo adLogInfo) {
////                JLUtils.setPlatform(adLogInfo.getSdkType());
////                JLUtils.jlShowCallback(true, adLogInfo.getEcpm());
////                ADUtils.sendAdLog(adLogInfo);
////                Log.e(TAG, "onADPresent...");
////                if (adListener != null) {
////                    adListener.onADPresent(adLogInfo);
////                }
////            }
////
////            @Override
////            public void onADClicked(AdLogInfo adLogInfo) {
////                JLUtils.setPlatform(adLogInfo.getSdkType());
////                JLUtils.jlClickCallback();
////                ADUtils.sendAdLog(adLogInfo);
////                Log.e(TAG, "onADClicked...");
////                if (adListener != null) {
////                    adListener.onADClicked(adLogInfo);
////                }
////            }
////
////            @Override
////            public void onADSkip(AdLogInfo adLogInfo) {
////                Log.e(TAG, "onADSkip...");
////                ADUtils.sendAdLog(adLogInfo);
////                if (adListener != null) {
////                    adListener.onADSkip(adLogInfo);
////                }
////            }
////
////            @Override
////            public void onADTimeOver(AdLogInfo adLogInfo) {
////                Log.e(TAG, "onADTimeOver...");
////                ADUtils.sendAdLog(adLogInfo);
////                if (adListener != null) {
////                    adListener.onADTimeOver(adLogInfo);
////                }
////            }
////        });
//    }

    /**
     * 加载插屏广告
     *
     * @param activity activity
     */
    public void showInterstitialAD(final Activity activity) {
//        showInterstitialAD(activity, null);
    }

    /**
     * 加载插屏广告
     *
     * @param activity activity
     * @param listener listener
     */
//    public void showInterstitialAD(final Activity activity, final OnInterstitialADListener listener) {
//        if (iad != null) {
//            iad.closeAD();
//            iad.destroy();
//            iad = null;
//        }
//        getInterstitialAD(activity, new com.qq.e.o.ads.v2.ads.interstitial.InterstitialADListener() {
//            @Override
//            public void onADReceive() {
//                Log.i(TAG, "InterstitialAD onADReceive");
//            }
//
//            @Override
//            public void onADPresent(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlShowCallback(false, adLogInfo.getEcpm());
//                ADUtils.sendAdLog(adLogInfo);
//                Log.i(TAG, "InterstitialAD onADPresent");
//            }
//
//            @Override
//            public void onADClicked(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlClickCallback();
//                ADUtils.sendAdLog(adLogInfo);
//                Log.i(TAG, "InterstitialAD onADClicked");
//            }
//
//            @Override
//            public void onADClosed(AdLogInfo adLogInfo) {
//                ADUtils.sendAdLog(adLogInfo);
//                Log.i(TAG, "InterstitialAD onADClose");
//            }
//
//            @Override
//            public void onSuccess(int i) {
//                if (listener != null) {
//                    listener.onShow();
//                }
//            }
//
//            @Override
//            public void onFailed(int i, AdError adError) {
//                Log.i(TAG, "InterstitialAD onFailed, eCode=" + adError.getErrorCode() + " msg:" + adError.getErrorMsg());
//            }
//        });
//        iad.loadAD();
//    }

//    private void getInterstitialAD(Activity activity, com.qq.e.o.ads.v2.ads.interstitial.InterstitialADListener adListener) {
//        if (iad != null) {
//            iad.closeAD();
//            iad.destroy();
//            iad = null;
//        }
//        iad = new InterstitialAD(activity, HXADConfig.getAicsKey(activity, HXADConfig.AD_TYPE.INTERSTITIAL), adListener);
//    }

    /**
     * 加载原生信息流广告
     *
     * @param activity    activity
     * @param adContainer 容器
     * @param adWidth     广告宽度（dp）
     * @param adHeight    广告高度（dp）
     * @param adStyle     广告样式（参照HXInfoAdStyle类）
     */
    public void showNativeAD(final Activity activity, final ViewGroup adContainer, final int adWidth, final int adHeight, final int adStyle, final boolean isPreload) {
        showNativeAD(activity, adContainer, adWidth, adHeight, adStyle, isPreload, null);
    }

    /**
     * 加载原生信息流广告
     *
     * @param activity    activity
     * @param adContainer 容器
     * @param adWidth     广告宽度（dp）
     * @param adHeight    广告高度（dp）
     * @param adStyle     广告样式（参照HXInfoAdStyle类）
     */
    public void showNativeAD(final Activity activity, final ViewGroup adContainer, final int adWidth, final int adHeight, final int adStyle, final boolean isPreload, final OnNativeVideoADListener onNativeVideoADListener) {
//        showNativeAD(activity, adContainer, adWidth, adHeight, adStyle, isPreload, true, onNativeVideoADListener);
    }

    /**
     * 加载原生信息流广告
     *
     * @param activity    activity
     * @param adContainer 容器
     * @param adWidth     广告宽度（dp）
     * @param adHeight    广告高度（dp）
     * @param adStyle     广告样式（参照HXInfoAdStyle类）
     * @param mAutoRender false:回调onSuccess   true:不回调
     */
//    public void showNativeAD(final Activity activity, final ViewGroup adContainer, final int adWidth, final int adHeight, final int adStyle, final boolean isPreload, final boolean mAutoRender, final OnNativeVideoADListener onNativeVideoADListener) {
//        nad = new NativeAD(activity, HXADConfig.getAicsKey(activity, Integer.parseInt(HXADConfig.AD_TYPE.NATIVE + "" + adStyle)), adContainer, adWidth, adHeight, adStyle, new NativeADListener() {
//            @Override
//            public void onSuccess(int i, View view) {
//                Log.e(TAG, "AdManager Native show Success");
//                if (onNativeVideoADListener != null) {
//                    onNativeVideoADListener.onShow(view);
//                    nad.render();
//                }
//            }
//
//            @Override
//            public void onFailed(int i, AdError adError) {
//                Log.e(TAG, "adError -> " + adError.getErrorMsg());
//                if (onNativeVideoADListener != null) {
//                    onNativeVideoADListener.onError();
//                }
//            }
//
//            @Override
//            public void onADPresent(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlShowCallback(false, adLogInfo.getEcpm());
//                ADUtils.sendAdLog(adLogInfo);
//                if (onNativeVideoADListener != null) {
//                    onNativeVideoADListener.onSuccess();
//                }
//            }
//
//            @Override
//            public void onADClicked(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlClickCallback();
//                ADUtils.sendAdLog(adLogInfo);
//                if (onNativeVideoADListener != null) {
//                    onNativeVideoADListener.onClick();
//                }
//            }
//
//            @Override
//            public void onADClosed(AdLogInfo adLogInfo) {
//                ADUtils.sendAdLog(adLogInfo);
//                Log.w(TAG, "NativeAD onADClosed");
//                if (isPreload) {
//                    showNativeAD(activity, adContainer, adWidth, adHeight, adStyle, true);
//                }
//                if (onNativeVideoADListener != null) {
//                    onNativeVideoADListener.onClosed();
//                }
//            }
//
//            @Override
//            public void onPreload() {
//
//            }
//        }, mAutoRender);
//        if (isPreload) {
//            nad.preloadAD();
//        } else {
//            nad.loadAD();
//            Log.e(TAG, "开始加载原生广告");
//        }
//    }

    /**
     * 加载横幅广告
     *
     * @param activity    activity
     * @param adContainer 容器
     * @param adHeight    广告高度（dp）
     */
//    public void showBannerAD(Activity activity, ViewGroup adContainer, int adHeight) {
//        bad = new BannerAD(activity, HXADConfig.getAicsKey(activity, HXADConfig.AD_TYPE.BANNER), adContainer, adHeight, new BannerADListener() {
//
//            @Override
//            public void onSuccess(int i) {
//
//            }
//
//            @Override
//            public void onFailed(int i, AdError adError) {
//                Log.i(TAG, "BannerAD onFailed, eCode=" + adError.getErrorCode() + " msg:" + adError.getErrorMsg());
//            }
//
//            @Override
//            public void onADPresent(AdLogInfo adLogInfo) {
//                Log.i(TAG, "BannerAD onADPresent");
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                ADUtils.sendAdLog(adLogInfo);
//                JLUtils.jlShowCallback(false, adLogInfo.getEcpm());
//            }
//
//            @Override
//            public void onADClicked(AdLogInfo adLogInfo) {
//                Log.i(TAG, "BannerAD onADClicked");
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                ADUtils.sendAdLog(adLogInfo);
//                JLUtils.jlClickCallback();
//            }
//
//            @Override
//            public void onADClosed(AdLogInfo adLogInfo) {
//                Log.i(TAG, "BannerAD onADClosed");
//                ADUtils.sendAdLog(adLogInfo);
//                closeBannerAD();
//            }
//        });
//        bad.loadAD();
//    }

    /**
     * 关闭横幅广告
     */
//    public void closeBannerAD() {
//        if (bad != null) {
//            bad.destroy();
//            bad = null;
//        }
//    }

    public void loadFullscreenVideoAD(final Activity activity, final boolean isPreload) {
//        loadFullscreenVideoAD(activity, isPreload, null);
    }

    /**
     * 预加载或加载全屏视频广告
     *
     * @param activity  activity
     * @param isPreload 是否预加载
     */
//    public void loadFullscreenVideoAD(final Activity activity, final boolean isPreload, final OnFullscreenVideoADListener adListener) {
//        getFullscreenVideoAD(activity, new FullscreenVideoADListener() {
//
//            @Override
//            public void onADLoad() {
//                Log.i(TAG, "FullscreenVideoAD onADLoad");
//            }
//
//            @Override
//            public void onVideoCached(AdLogInfo adLogInfo) {
//                Log.i(TAG, "FullscreenVideoAD onVideoCached");
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onADShow() {
//                Log.i(TAG, "FullscreenVideoAD onADShow");
//            }
//
//            @Override
//            public void onADPresent(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlShowCallback(false, adLogInfo.getEcpm());
//                ADUtils.sendAdLog(adLogInfo);
//                Log.i(TAG, "FullscreenVideoAD onADExpose");
//            }
//
//            @Override
//            public void onADClicked(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlClickCallback();
//                ADUtils.sendAdLog(adLogInfo);
//                Log.i(TAG, "FullscreenVideoAD onADClicked");
//            }
//
//            @Override
//            public void onVideoComplete(AdLogInfo adLogInfo) {
//                ADUtils.sendAdLog(adLogInfo);
//                Log.i(TAG, "FullscreenVideoAD onVideoComplete");
//            }
//
//            @Override
//            public void onADClosed(AdLogInfo adLogInfo) {
//                Log.i(TAG, "FullscreenVideoAD onADClosed");
//                ADUtils.sendAdLog(adLogInfo);
//                if (adListener != null) {
//                    adListener.onClosed();
//                }
//                if (fvAdListener != null) {
//                    fvAdListener.onClosed();
//                }
//                if (isPreload) {
//                    loadFullscreenVideoAD(activity, true);
//                }
//            }
//
//            @Override
//            public void onSuccess(int i) {
//
//            }
//
//            @Override
//            public void onFailed(int i, AdError adError) {
//                Log.i(TAG, "FullscreenVideoAD onFailed, eCode=" + adError.getErrorCode() + " msg:" + adError.getErrorMsg());
//                if (adListener != null) {
//                    adListener.onFailed(i, adError);
//                }
//                if (fvAdListener != null) {
//                    fvAdListener.onFailed(i, adError);
//                }
//            }
//
//            @Override
//            public void onSkippedVideo(AdLogInfo adLogInfo) {
//                Log.i(TAG, "FullscreenVideoAD onSkippedVideo");
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onPreload() {
//                Log.i(TAG, "FullscreenVideoAD onPreload");
//            }
//        });
//        if (isPreload) {
//            fvAd.preloadAD();
//        } else {
//            fvAd.loadAD();
//        }
//    }

//    private void getFullscreenVideoAD(Activity activity, FullscreenVideoADListener adListener) {
//        fvAd = new FullscreenVideoAD(activity, HXADConfig.getAicsKey(activity, HXADConfig.AD_TYPE.FULLSCREEN_VIDEO), adListener);
//    }

    public void loadRewardVideoAD(final Activity activity, final boolean isPreload) {
//        loadRewardVideoAD(activity, isPreload, null);
    }

//    /**
//     * 预加载或加载激励视频广告
//     *
//     * @param activity  activity
//     * @param isPreload 是否预加载
//     */
//    public void loadRewardVideoAD(final Activity activity, final boolean isPreload, final OnRewardVideoADListener adListener) {
//        Log.e(TAG, "准备加载激励视频广告");
//        getRewardVideoAD(activity, new RewardVideoADListener() {
//
//            @Override
//            public void onADLoad() {
//                Log.e(TAG, "RewardVideoAD onADLoad");
//            }
//
//            @Override
//            public void onVideoCached(AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onVideoCached: " + adLogInfo.toString());
//                adLogInfo.setAction(HXADConfig.AD_ACTION.VIDEO_CACHED);
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onADShow() {
//                Log.e(TAG, "广告展示，关闭Loading");
//                closeLoading("", activity);
//                ToastUtil.showLong(activity, "完整观看视频才能获得相应红包奖励哦");
//            }
//
//            @Override
//            public void onADPresent(AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onADPresent: " + adLogInfo.toString());
//                adLogInfo.setAction(HXADConfig.AD_ACTION.SHOW);
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlShowCallback(false, adLogInfo.getEcpm());
//                ADUtils.sendAdLog(adLogInfo);
//                if (adListener != null) {
//                    adListener.onShow(adLogInfo.getEcpm());
//                }
//                if (rvAdListener != null) {
//                    rvAdListener.onShow(adLogInfo.getEcpm());
//                }
//            }
//
//            @Override
//            public void onReward(final AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onReward: " + adLogInfo.toString());
//                adLogInfo.setAction(HXADConfig.AD_ACTION.VIDEO_REWARD);
//                ADUtils.sendAdLog(adLogInfo, new ADUtils.AdLogListener() {
//                    @Override
//                    public void onSuccess() {
//                        Log.e(TAG, "reward onSuccess");
//                        isRewardSendSus = true;
//                        if (isRewardClosed && !isRewardCallBacked) {
//                            Log.e(TAG, "reward onClose by sendAdLog");
//                            if (adListener != null && rvAdListener != null) {
//                                Log.e(TAG, "reward error");
//                            }
//                            if (adListener != null) {
//                                adListener.onClosed(adLogInfo.getOrderId());
//                            }
//                            if (rvAdListener != null) {
//                                rvAdListener.onClosed(adLogInfo.getOrderId());
//                            }
//                            isRewardCallBacked = true;
//                        }
//                    }
//                });
//
//                if (adListener != null) {
//                    adListener.onReward();
//                }
//                if (rvAdListener != null) {
//                    rvAdListener.onReward();
//                }
//            }
//
//            @Override
//            public void onRewardVerify(RewardInfo rewardInfo, AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onRewardVerify: " + rewardInfo.toString() + adLogInfo.toString());
//                UMManager.onEvent(UMManager.Event.IncentiveValidations_num);
//
//                if (rewardInfo.errCode == 0 || rewardInfo.errCode == 20000) {
//                    UMManager.onEvent(UMManager.Event.IncentiveValidations_num_correct);
//                    adLogInfo.setHasLegal(1);
//                    Log.e(TAG, "rewardVerify--true");
//                } else {
//                    adLogInfo.setHasLegal(0);
//                    Log.e(TAG, "rewardVerify--false");
//                }
//                adLogInfo.setAction(HXADConfig.AD_ACTION.VIDEO_REWARD_VERIFY);
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onADClicked(AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onADClicked: " + adLogInfo.toString());
//                adLogInfo.setAction(HXADConfig.AD_ACTION.CLICK);
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlClickCallback();
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onVideoComplete(AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onVideoComplete: " + adLogInfo.toString());
//                adLogInfo.setAction(HXADConfig.AD_ACTION.VIDEO_COMPLETE);
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onADClosed(AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onADClosed: " + adLogInfo.toString());
//                adLogInfo.setAction(HXADConfig.AD_ACTION.CLOSED);
//                ADUtils.sendAdLog(adLogInfo);
//
//                isRewardClosed = true;
//                if (isRewardSendSus && !isRewardCallBacked) {
//                    Log.e(TAG, "reward onClose by onADClosed");
//                    if (adListener != null && rvAdListener != null) {
//                        Log.e(TAG, "reward error");
//                    }
//                    if (adListener != null) {
//                        adListener.onClosed(adLogInfo.getOrderId());
//                    }
//                    if (rvAdListener != null) {
//                        rvAdListener.onClosed(adLogInfo.getOrderId());
//                    }
//                    isRewardCallBacked = true;
//                }
//
//                if (isPreload) {
//                    loadRewardVideoAD(activity, true);
//                }
//
//            }
//
//            @Override
//            public void onSuccess(int i) {
//
//            }
//
//            @Override
//            public void onFailed(int i, AdError adError) {
//                Log.e(TAG, "RewardVideoAD onFailed, eCode=" + adError.getErrorCode() + " msg:" + adError.getErrorMsg());
//                if (handler != null) {
//                    Log.e(TAG, "广告加载失败，关闭Loading");
//                    closeLoading("加载广告失败", activity);
//                }
//                if (!isPreload) {
//                    if (adListener != null) {
//                        adListener.onFailed(i, adError);
//                    }
//                    if (rvAdListener != null) {
//                        rvAdListener.onFailed(i, adError);
//                    }
//                } else {
//                    Log.e(TAG, "广告预加载失败");
//                }
//            }
//
//            @Override
//            public void onSkippedVideo(AdLogInfo adLogInfo) {
//                Log.e(TAG, "RewardVideoAD onSkippedVideo");
//                adLogInfo.setAction(HXADConfig.AD_ACTION.SKIPPED);
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onPreload() {
//                Log.e(TAG, "RewardVideoAD onPreload");
//            }
//
//            @Override
//            public void onADTimeout() {
//                Log.e(TAG, "RewardVideoAD onADTimeout");
//                if (handler != null) {
//                    Log.e(TAG, "广告加载超时，关闭Loading");
//                    closeLoading("加载广告超时", activity);
//                }
//                if (!isPreload) {
//                    if (adListener != null) {
//                        adListener.onTimeout();
//                    }
//                    if (rvAdListener != null) {
//                        rvAdListener.onTimeout();
//                    }
//                } else {
//                    Log.e(TAG, "广告预加载超时");
//                }
//            }
//        });
//        if (isPreload) {
//            rvAd.preloadAD();
//        } else {
//            rvAd.loadAD();
//        }
//    }

//    private void getRewardVideoAD(Activity activity, RewardVideoADListener adListener) {
//        rvAd = new RewardVideoAD(activity, HXADConfig.getAicsKey(activity, HXADConfig.AD_TYPE.REWARD_VIDEO), adListener);
//    }

//    public RewardVideoAD getRvAd() {
//        return rvAd;
//    }

    //  加载广告
//    public void loadNativeAd(final Activity a, int widthDp, int heightDp, int adType, final InterfaceNativeADLoad lis) {
//        new NativeAD(a, HXADConfig.getAicsKey(a, Integer.parseInt(HXADConfig.AD_TYPE.NATIVE + "" + adType)), null, widthDp, heightDp, adType, new NativeADListener() {
//            @Override
//            public void onSuccess(int i, View view) {
//                lis.success(view);
//            }
//
//            @Override
//            public void onFailed(int i, AdError adError) {
//                Log.e(TAG, "NativeAD onFailed, eCode=" + adError.getErrorCode() + " msg:" + adError.getErrorMsg());
//            }
//
//            @Override
//            public void onADPresent(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlShowCallback(false, adLogInfo.getEcpm());
//                ADUtils.sendAdLog(adLogInfo);
//                Log.e(TAG, "NativeAD onADPresent");
//            }
//
//            @Override
//            public void onADClicked(AdLogInfo adLogInfo) {
//                JLUtils.setPlatform(adLogInfo.getSdkType());
//                JLUtils.jlClickCallback();
//                ADUtils.sendAdLog(adLogInfo);
//                Log.e(TAG, "NativeAD onADClicked");
//            }
//
//            @Override
//            public void onADClosed(AdLogInfo adLogInfo) {
//                Log.e(TAG, "NativeAD onADClosed");
//                ADUtils.sendAdLog(adLogInfo);
//            }
//
//            @Override
//            public void onPreload() {
//                Log.e(TAG, "NativeAD onPreload");
//            }
//        }, false).loadAD();
//    }

    public interface OnNativeVideoADListener {
        void onSuccess();

        void onClosed();

        void onError();

        void onClick();

        void onShow(View view);
    }

    public interface InterfaceNativeADLoad {
        void success(View v);
    }

    public interface OnFullscreenVideoADListener {
        void onClosed();

        void onFailed(int i, int code);
    }

    public interface OnRewardVideoADListener {
        void onClosed(String orderId);

        void onReward();

        void onShow(double ecpm);

        void onFailed(int i, int code);

        void onFailed(int i, Exception adError);

        void onTimeout();
    }

    public interface OnInterstitialADListener {
        void onShow();
    }


    private static String getAdType(int type) {
        switch (type) {

            case TTAdConstant.AD_TYPE_COMMON_VIDEO:
                return "普通激励视频，type=" + type;

            case TTAdConstant.AD_TYPE_PLAYABLE_VIDEO:
                return "Playable激励视频，type=" + type;

            case TTAdConstant.AD_TYPE_PLAYABLE:
                return "纯Playable，type=" + type;

            case TTAdConstant.AD_TYPE_LIVE:
                return "直播流，type=" + type;
        }

        return "未知类型+type=" + type;
    }
}